class Member < ActiveRecord::Base
  has_and_belongs_to_many :posts, :join_table => :likes
  
  def likes? ( post )
    
    return self.posts.include? post
    
  end
  
  def tags  
    liked_tags = Hash.new
    
    self.posts.each do |post|
      post.includes.each do |include|
        
        if liked_tags.has_key? include.tag.content
          liked_tags[include.tag.content] += include.cardinality
        else
          liked_tags[include.tag.content] = include.cardinality
        end
        
      end
    end
    return liked_tags
  end
  
  def sorted_tags
    return self.tags.sort {|a,b| b[1]<=>a[1]}
  end
  
  def similarity( post )
    
    my_tags = tags
    common_tags_cardinality_sum = 0
    my_tags_cardinality_sum = 0
    post_tags_cardinality_sum = 0
    
    # zbrajanje kardinalnosti posta i umnozaka kardinalnosti zajednickih tagova
    post.includes.each do |include|
      post_tags_cardinality_sum += include.cardinality ** 2
      
      if my_tags.has_key? include.tag.content
        my_tag_cardinality = my_tags[include.tag.content]
        post_tag_cardinality = include.cardinality
        
        puts "Tag in common: " + include.tag.content
        
        common_tags_cardinality_sum += my_tag_cardinality * post_tag_cardinality
      end
    end
    
    # zbrajanje korisnikovih kardinalnosti tagova
    my_tags.each do |tag, cardinality|
      my_tags_cardinality_sum += cardinality ** 2
    end
    
    score = (common_tags_cardinality_sum * 100 / ( Math.sqrt(my_tags_cardinality_sum) * Math.sqrt(post_tags_cardinality_sum) ) ) 
    puts "common_tags_cardinality_sum: "+ common_tags_cardinality_sum.to_s
    puts "my_tags_cardinality_sum: " + my_tags_cardinality_sum.to_s
    puts "post_tags_cardinality_sum: " + post_tags_cardinality_sum.to_s
    puts "Score: " + score.to_s
    return score
    
  end
  
  def tags_in_common( post )
    common_tags = Array.new
    my_tags = self.tags
    
    post.tags.each do |tag|
      if my_tags.has_key? tag.content
        common_tags.push tag.content
      end
    end
    
    return common_tags
  end
  
  
end
